// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if(arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function showTree(root) {
  if(root == null)
    return ;
  // 层次遍历
  let NodeArr = [],
    value = [];
  NodeArr.push(root);
  value.push(root.val);
  while (NodeArr.length) {
    let tempNode = NodeArr[0];
    NodeArr = NodeArr.slice(1, NodeArr.length);
    if (tempNode == null) continue;
    if (tempNode.left) {
      NodeArr.push(tempNode.left);
      value.push(tempNode.left.val);
    }
    if (tempNode.right) {
      NodeArr.push(tempNode.right);
      value.push(tempNode.right.val);
    }
  }
  for (let i = 0; i < value.length; i++)
    console.log(value[i]);
}
var inorderTraversal = function (root) {
  let arr = [], stack = [];
  // 1.递归
  // function midOrder(node) {
  //   if(node == null)
  //     return ;
  //   midOrder(node.left);
  //   arr.push(node.val);
  //   midOrder(node.right);
  // }
  // midOrder(root);
  // 2.迭代
  while (root || stack.length) {
    while (root) {
      stack.push(root);
      root = root.left;
    }
    root = stack.pop();
    result.push(root.val);
    root = root.right;
  }
  return arr;
};
let root = [1, null, 2, 3];
console.log(inorderTraversal(root));
root = [];
console.log(inorderTraversal(root));
root = [1];
console.log(inorderTraversal(root));
